//    Openbravo POS is a point of sales application designed for touch screens.
//    Copyright (C) 2007-2009 Openbravo, S.L.
//    http://www.openbravo.com/product/pos
//
//    This file is part of Openbravo POS.
//
//    Openbravo POS is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    Openbravo POS is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with Openbravo POS.  If not, see <http://www.gnu.org/licenses/>.

package cn.ekuma.epos.qkorder;

import cn.ekuma.data.dao.ListKeyed;
import cn.ekuma.data.dao.bean.IKeyed;
import cn.ekuma.data.ui.swing.JEditorWarpDialog;
import cn.ekuma.epos.bean.util.erp.OrderHelper;
import cn.ekuma.epos.bean.util.erp.OrderLine_P;
import cn.ekuma.epos.module.ERPSecurityManager;
import cn.ekuma.epos.module.ERP_UI_Swing_Model;
import cn.ekuma.epos.order.JOrderLines;
import cn.ekuma.epos.productsfinishing.ProductsEditor;
import cn.ekuma.epos.qkorder.dialog.JOrderLineEditDialog;
import cn.ekuma.epos.qkorder.dialog.JTxtImportDialog;
import cn.ekuma.epos.qkorder.ordermanager.PageChangeListener;
import cn.ekuma.epos.qkorder.ordermanager.PageChangeEvent;
import cn.ekuma.epos.qkorder.ordermanager.OrderManager;
import cn.ekuma.epos.businesslogic.OrderUtil;
import cn.ekuma.epos.businesslogic.RoleUtil;
import cn.ekuma.epos.core.util.ProductSwingUtil;

import java.util.Map.Entry;

import javax.swing.*;

import java.awt.*;
import java.awt.image.BufferedImage;

import com.openbravo.data.gui.ComboBoxValEntry;
import com.openbravo.data.gui.ComboBoxValModel;
import com.openbravo.data.gui.MessageInf;
import com.openbravo.pos.printer.*;
import com.openbravo.pos.forms.JPanelView;
import com.openbravo.pos.forms.JRootApp;
import com.openbravo.pos.base.AbstractPosApp;
import com.openbravo.pos.base.AppView;
import com.openbravo.pos.base.AppLocal;
import com.openbravo.pos.base.I_AppView;
import com.openbravo.pos.base.I_ScriptCommand;
import com.openbravo.pos.base.ScriptArg;
import com.openbravo.pos.scale.ScaleException;
import com.openbravo.data.basic.BasicException;
import com.openbravo.bean.BusinessPartner;

import cn.ekuma.epos.datalogic.I_DataLogicCustomers;
import cn.ekuma.epos.datalogic.I_DataLogicERP;
import cn.ekuma.epos.datalogic.I_DataLogicReceipts;

import com.openbravo.pos.scripting.ScriptEngine;
import com.openbravo.pos.scripting.ScriptException;
import com.openbravo.pos.scripting.ScriptFactory;

import cn.ekuma.epos.datalogic.I_DataLogicSystem;
import cn.ekuma.epos.datalogic.businesslogic.OrderCalcManager;
import cn.ekuma.epos.datalogic.businesslogic.OrderRuleManager;
import cn.ekuma.epos.datalogic.businesslogic.orderrule.RuleMessage;
import cn.ekuma.epos.datalogic.define.DataLogicSystemHelper;
import cn.ekuma.epos.db.table.I_Product;
import cn.ekuma.epos.report.JReportDialog;
import cn.ekuma.epos.servings.JServingsEditorDialog;
import cn.ekuma.rabbit.spi.I_ModelPart;
import cn.ekuma.security.I_SecurityManager;
import cn.ekuma.security.I_SecurityObject;
import cn.ekuma.util.MoneyUtil;

import com.openbravo.beans.JNumberDialog;
import com.openbravo.basic.LocaleResources;
import com.openbravo.data.gui.JMessageDialog;
import com.openbravo.data.user.DirtyManager;
import com.openbravo.def.ERPPermission;
import com.openbravo.format.Formats;
import com.openbravo.pos.base.BeanFactoryApp;
import com.openbravo.pos.base.BeanFactoryException;
import com.openbravo.bean.TaxCategory;
import com.openbravo.bean.Tax;
import com.openbravo.bean.erp.Order;
import com.openbravo.bean.erp.OrderLine;
import com.openbravo.bean.erp.ordercalc.OrderTypeCalcConfig;
import com.openbravo.bean.erp.viewbean.OrderLineConsultInfo;
import com.openbravo.bean.erp.OrderType;
import com.openbravo.pos.customers.CustomersEditor;
import com.openbravo.pos.panels.JCustomerFinder;
import com.openbravo.pos.panels.JPanelButtons;
import com.openbravo.pos.panels.JProductAttEdit;
import com.openbravo.pos.panels.JProductFinder;
import com.openbravo.pos.panels.event.CustomerChangedListener;
import com.openbravo.pos.panels.event.ProductChangedListener;
import com.openbravo.pos.panels.navigator.JCustomerNavigator;
import com.openbravo.pos.payment.JPaymentSelect;
import com.openbravo.pos.payment.JPaymentSelectOrderFundIn;
import com.openbravo.pos.sales.JChangeRateDialog;
import com.openbravo.pos.sales.JTicketLinePropEdit;
import com.openbravo.bean.erp.OrderState;
import com.openbravo.bean.infobean.CustomerInfo;
import com.openbravo.bean.AppUser;
import com.openbravo.bean.PaymentInfo;
import com.openbravo.bean.Product;
import com.openbravo.bean.Serving;
import com.openbravo.pos.bean.ProductExt;
import com.openbravo.bean.shard.UserOrderTypePermission;
import com.openbravo.pos.sales.TaxesException;
import com.openbravo.pos.sales.TaxesLogic;
import com.openbravo.pos.sales.JCatalogKeyBoardDialog;
import com.openbravo.pos.util.PaymentInfoList;

import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.FilenameFilter;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.Properties;
import java.util.ResourceBundle;

import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.xml.JRXmlLoader;

import org.drools.KnowledgeBase;
import org.drools.KnowledgeBaseFactory;
import org.drools.builder.KnowledgeBuilder;
import org.drools.builder.KnowledgeBuilderError;
import org.drools.builder.KnowledgeBuilderErrors;
import org.drools.builder.KnowledgeBuilderFactory;
import org.drools.builder.ResourceType;
import org.drools.io.ResourceFactory;
import org.drools.runtime.StatefulKnowledgeSession;
import org.ofsm.IState;
import org.ofsm.IStateChangeListener;
import org.ofsm.IStateTransition;
//Openbravo POS is a point of sales application designed for touch screens.

/**
*
* @author adrianromero
*/
public abstract class JPanelOrder extends JPanel implements JPanelView, BeanFactoryApp, OrdersEditor,ProductChangedListener,I_ScriptCommand,I_ModelPart<ERP_UI_Swing_Model> ,I_SecurityObject{

// Variable numerica
private final static int NUMBERZERO = 0;
private final static int NUMBERVALID = 1;

private final static int NUMBER_INPUTZERO = 0;
private final static int NUMBER_INPUTZERODEC = 1;
private final static int NUMBER_INPUTINT = 2;
private final static int NUMBER_INPUTDEC = 3; 
private final static int NUMBER_PORZERO = 4; 
private final static int NUMBER_PORZERODEC = 5; 
private final static int NUMBER_PORINT = 6; 
private final static int NUMBER_PORDEC = 7; 

protected JOrderLines m_Orderlines;
  
// private Template m_tempLine;
private TicketParser m_TTP;

protected Order m_oOrder;
protected Object m_oOrderExt;

// Estas tres variables forman el estado...
private int m_iNumberStatus;
private int m_iNumberStatusInput;
private int m_iNumberStatusPor;

      
private JOrdersBag m_Ordersbag;

private ListKeyed taxcollection;
// private ComboBoxValModel m_TaxModel;

private ListKeyed taxcategoriescollection;
private ComboBoxValModel taxcategoriesmodel;

private TaxesLogic taxeslogic;

//private ScriptObject scriptobjinst;
protected JPanelButtons m_jbtnconfig;

protected JRootApp m_App;
protected I_DataLogicSystem dlSystem;
protected I_DataLogicERP dlSales;
protected I_DataLogicCustomers dlCustomers;
protected I_DataLogicReceipts dlReceipts;

private JPaymentSelect paymentdialog;
//private JPaymentKeyBoardSelect paymentdialogfundout;

private JCatalogKeyBoardDialog catalogDialog;

protected OrderManager orderManager;

private static LocaleResources reportLocale;

private JProductFinder productFinder;

private JEditorWarpDialog productCreateDialog,customerCreateDialog;
//private JProductDetail productDetail;
private JCustomerNavigator customerNavigator;
private OrderRuleManager orderRuleManager;
private OrderCalcManager orderCalcManager;

/** Creates new form JOrderView */
public JPanelOrder() {
  initComponents ();
}

@Override
public void init(I_AppView app) throws BeanFactoryException {
  m_App = (JRootApp) app;
  dlSystem = mode.getDLSystem();
  dlSales = mode.getDLERP();
  dlCustomers = mode.getDLCustomer();
  dlReceipts=mode.getDLReceipts();
  orderManager=new OrderManager(dlSystem);
  orderManager.addPageChangeListener(new PageChangeListener(){
          @Override
          public void pageChanged(PageChangeEvent event) {
              refreshOrder();
          }
  });

  
  orderRuleManager=new OrderRuleManager();
  orderRuleManager.init(AbstractPosApp.pmf);
  orderManager.addStateChangeListener(new IStateChangeListener(){
      public boolean onStateChanging(IStateTransition transition) {
    	  Order tempOrder=getActiveOrder();
          if(tempOrder.getLinesCount()==0){
              new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.noOrderLine")).show(JPanelOrder.this);
              return false;
          }
          IState fromState=transition.getFromState();
          List<RuleMessage> ret=null;
          if(fromState.getName().equalsIgnoreCase(AppLocal.getIntString(OrderState.ORDERSTATE_Start))){
          	try {
					ret=orderRuleManager.isPass(dlSales, m_oOrder);
				} catch (BasicException e) {
					e.printStackTrace();
					return false;
				}
				if(ret!=null){
					String messsage="";
					for(RuleMessage r:ret)
						messsage=messsage+r.getOrderLine()+":"+r.getMessage()+"\n";
					new MessageInf(MessageInf.SGN_WARNING, messsage).show(JPanelOrder.this);
					return false;
				}
          }
          
          try { 
              getReCalcActiveOrder();
          } catch (TaxesException e) {
              MessageInf msg = new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.cannotcalculatetaxes"));
              msg.show(JPanelOrder.this);
          } catch (BasicException e) {
          	 new MessageInf(MessageInf.SGN_WARNING, e.getMessage()).show(JPanelOrder.this);
        }
          
          IState toState=transition.getToState();
          if(toState.getName().equalsIgnoreCase(AppLocal.getIntString(OrderState.ORDERSTATE_End))){
              if(!isOrderPaymented()){
                  new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.noPaymented")).show(JPanelOrder.this);
                  return false;
                }
                int res = JOptionPane.showConfirmDialog(JPanelOrder.this, AppLocal.getIntString("message.wannacloseorder"), AppLocal.getIntString("title.editor"), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
                if (res == JOptionPane.NO_OPTION) {
                       return false;
                 }
          }
		 if (tempOrder.getDefineType().isCheckRule()) {
					byte[] drlText = dlSystem.getResourceAsBinary("rule.order."+ tempOrder.getDefineType().getName());
					if (drlText != null) {
						KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
						kbuilder.add(ResourceFactory.newByteArrayResource(drlText),ResourceType.DRL);
						KnowledgeBuilderErrors errors = kbuilder.getErrors();
						if (errors.size() > 0) {
							String messsage="";
							for (KnowledgeBuilderError error : errors) {
								messsage=messsage+error.getMessage()+"\n";
							}
							new MessageInf(MessageInf.SGN_WARNING, messsage).show(JPanelOrder.this);
							return false;
						}
						KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
						kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());
						
						StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
						// go !
						boolean isPass=true;
						List<RuleMessage> retMessages=new ArrayList<RuleMessage>();
						ksession.insert(tempOrder);
						ksession.insert(isPass);
						ksession.insert(retMessages);
						ksession.fireAllRules();
						if(!isPass){
							String messsage="";
							for(RuleMessage r:retMessages)
								messsage=messsage+r.getOrderLine()+":"+r.getMessage()+"\n";
							new MessageInf(MessageInf.SGN_WARNING, messsage).show(JPanelOrder.this);
							return false;
						}
					}else
						new MessageInf(MessageInf.SGN_WARNING, "没能找到单据的对应规则定义，单类："+tempOrder.getDefineType().getName()).show(JPanelOrder.this);
          }
          return true;
      }

      public void onStateChanged(IStateTransition transition,String memo) {
          IState toState=transition.getToState();
          if(toState.getName().equalsIgnoreCase(AppLocal.getIntString(OrderState.ORDERSTATE_End))){
              if (closeOrder(m_oOrder, memo)) {
                  // Ends edition of current receipt 
                  orderManager.setEditAble(false);
                  refreshEditModel();
                  resetSouthComponent();
              }else {
                  // repaint current order
                  refreshOrder();
              }
          }else{
              m_oOrder.addState(new OrderState(m_App.getAppUserView().getUser().getUserInfo(),toState.getName(),memo));
          }
      }
  }
  );
  
  
  orderCalcManager=new OrderCalcManager();
  orderCalcManager.init(mode.getManager().getPluginManager());
  
  m_Ordersbag = getJOrdersBag();
  m_jPanelBag.add(m_Ordersbag.getBagComponent(), BorderLayout.LINE_START);
  add(m_Ordersbag.getNullComponent(), "null");

  //m_Orderlines = new JOrderLines(dlSystem.getResourceAsXML("Order.Line"));
  //m_jPanelCentral.add(m_Orderlines, java.awt.BorderLayout.CENTER);
  
  m_TTP = new TicketParser(m_App.getDeviceTicket(), dlSystem);
         
  // Los botones configurables...
  m_jbtnconfig = new JPanelButtons("Order.Buttons", this);
  //m_jButtonsExt.add(m_jbtnconfig);
 
  splitPane.setRightComponent(getSouthComponent());
  // El panel de los productos o de las lineas...
  //catcontainer.add(getSouthComponent(), BorderLayout.CENTER);
  containerToolbar.add(getSouthComponentToolBar(),BorderLayout.NORTH);
  
  // El modelo de impuestos
  
  taxcategoriesmodel = new ComboBoxValModel();
  //productDetail=new JProductDetail(dlSales);
  //m_jPanOrder.add(productDetail, java.awt.BorderLayout.EAST);
  //productDetail.setVisible(false);
  
  customerNavigator=new JCustomerNavigator(dlSales);
  customerNavigator.addCustomerChangedListener(new CustomerChangedListener(){
	@Override
	public void valueSelectChanged(CustomerInfo obj) {
		m_Ordersbag.newOrder(obj);
	}
  });
  m_jPanOrder.add(customerNavigator, java.awt.BorderLayout.EAST);
  if(isCustomerView())
	  customerNavigator.setVisible(false);
  
  // ponemos a cero el estado
  stateToZero();  

  init2(m_App);
  // inicializamos
  m_oOrder = null;
  m_oOrderExt = null;
}

private boolean isOrderPaymented(){
  if (OrderType.FUNDTYPE_NoChange == m_oOrder.getDefineType().getFundType())
      return true;
  PaymentInfoList m_aPaymentInfo=new PaymentInfoList();
  for(PaymentInfo info:m_oOrder.getPayments())
       m_aPaymentInfo.add(info);
  return OrderHelper.getTotal(m_oOrder)==m_aPaymentInfo.getTotal();
}

public void init2(AppView app) throws BeanFactoryException {

  m_jKeyFactory.setActionMap(getKeyBoardActions());
  m_jKeyFactory.setInputMap(JTextField.WHEN_FOCUSED, getKeyBoardInputMap());
  
  m_jPrice.addMouseListener(new MouseListener(){

		@Override
		public void mouseClicked(MouseEvent e) {
			m_jKeyFactory.requestFocus();
		}

		@Override
		public void mousePressed(MouseEvent e) {
		}

		@Override
		public void mouseReleased(MouseEvent e) {
		}

		@Override
		public void mouseEntered(MouseEvent e) {
		}

		@Override
		public void mouseExited(MouseEvent e) {
		}
  	
  });
  
  loadReport();
}

private void buildOrderLinePanel(){
  if(m_Orderlines!=null)
        m_jPanelCentral.remove(m_Orderlines);
  String lineStyle="Order.Line";
  String lineColumnXML=dlSystem.getResourceAsXML(lineStyle+"."+m_oOrder.getDefineType().getName()+"."+m_App.getAppUserView().getUser().getName());
  if(lineColumnXML==null||lineColumnXML.isEmpty())
      lineColumnXML=dlSystem.getResourceAsXML(lineStyle+"."+m_oOrder.getDefineType().getName());
  if(lineColumnXML==null||lineColumnXML.isEmpty())
      lineColumnXML=dlSystem.getResourceAsXML(lineStyle);
  m_Orderlines = new JOrderLines(lineColumnXML);
  m_jPanelCentral.add(m_Orderlines, java.awt.BorderLayout.CENTER);
  m_Orderlines.addListSelectionListener(new ListSelectionListener() {
      @Override
      public void valueChanged(ListSelectionEvent e) {
         refreshOrderLineSelectedState();
      }
  });
}


private void loadReport(){
  String baseDirName="./reports/cn/ekuma/reports/order/";
  reportLocale=new LocaleResources();
  reportLocale.addBundleName("cn/ekuma/reports/order/report");

  File dir=new File(baseDirName);
  if(dir.isDirectory()){
      for(File reportFile:dir.listFiles(new FilenameFilter(){
          @Override
          public boolean accept(File dir, String name) {
              return name.endsWith(".jrxml");
          }
      })){
          String fileName=reportFile.getName().substring(0, reportFile.getName().lastIndexOf('.'));
          jReportCombo.addItem(new ComboBoxValEntry(fileName,reportLocale.getString(fileName)));
      }
  }
}

private ActionMap getKeyBoardActions() {
  ActionMap actionMap = new ActionMap();

  actionMap.put("Up", new M_jUpAction());
  actionMap.put("Down", new M_jDownAction());
  actionMap.put("Delete", new M_jDeleteAction());
  actionMap.put("EditAttributes", new M_jEditAttributesAction());
  actionMap.put("EditLine", new M_jEditLineAction());
  actionMap.put("EditProduct", new M_jEditProductAction());
  actionMap.put("Change Coustomer", new M_jChangeCoustomerAction());
  actionMap.put("Print", new M_jPrintAction());
  actionMap.put("FindProc", new M_jFindProdcutAction());


  actionMap.put("InsServings", new M_jInsServingsAction());
  actionMap.put("changeOrderRate", new M_jChangeOrderRateAction());
  actionMap.put("EditLineAttrib", new M_jEditLineAttribAction());
  actionMap.put("changeOrderType", new M_jChangeOrderTypeAction());
  actionMap.put("ShowQuickSell", new M_jQuickSellAction());
  actionMap.put("AddCustomer", new AddCustomerAction());

  actionMap.put("backSpace", new M_inputDeleteAction());
  actionMap.put("productDetail", new M_ProductDetailAction());
  actionMap.put("SavePageSort", new M_SavePageSortAction());
  
  actionMap.put("productRefush", new M_ProductRefushAction());
  return actionMap;
}

private InputMap getKeyBoardInputMap() {
  InputMap inputMap = new InputMap();
  inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), "Up");
  inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), "Down");
  inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "EditLine");
  inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), "EditAttributes");
  inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), "Delete");
  inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0), "Change Coustomer");
  inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_F4, 0), "changeOrderType");

  inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_F9, 0), "FindProc");
  inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_F10, 0), "ShowQuickSell");
  inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_F11, 0), "Print");

  inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, 0), "InsServings");
  inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_END, 0), "changeOrderRate");
  inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_HOME, 0), "EditLineAttrib");
  inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_F3, 0), "AddCustomer");

  inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, 0), "backSpace");
  
  inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_E,InputEvent.ALT_DOWN_MASK), "EditProduct");
  inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_F,InputEvent.ALT_DOWN_MASK), "productDetail");
  inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_S,InputEvent.ALT_DOWN_MASK), "SavePageSort");
  inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_C,InputEvent.ALT_DOWN_MASK), "productRefush");
  return inputMap;
}


@Override
public Object getBean() {
  return this;
}

@Override
public JComponent getComponent() {
  return this;
}

@Override
public void activate() throws BasicException {
  paymentdialog =JPaymentSelectOrderFundIn.getDialog(this);
  paymentdialog.init(m_App, dlSystem, dlSales, mode.getManager().getPluginManager(), security);
  m_jaddtax.setSelected(true);

  // Inicializamos el combo de los impuestos.
  java.util.List<Tax> taxlist = dlSales.list(Tax.class);
  taxcollection = new ListKeyed<Tax>(taxlist);
  java.util.List<TaxCategory> taxcategorieslist = dlSales.list(TaxCategory.class);
  taxcategoriescollection = new ListKeyed<TaxCategory>(taxcategorieslist);
  
  taxcategoriesmodel = new ComboBoxValModel(taxcategorieslist);
  m_jTax.setModel(taxcategoriesmodel);

  //String taxesid = m_jbtnconfig.getProperty("taxcategoryid");
  String taxesid =null;

  if (taxesid == null) {
      if (m_jTax.getItemCount() > 0) {
          m_jTax.setSelectedIndex(0);
      }
  } else
		taxcategoriesmodel.setSelectedKey(taxesid);              
          
  taxeslogic = new TaxesLogic(taxlist);
  
  orderCalcManager.setConfigs(dlSales.list(OrderTypeCalcConfig.class));
  
  // Show taxes options
  if (security.hasPermissionByName("order.ChangeTaxOptions")) {
      m_jTax.setVisible(true);
      m_jaddtax.setVisible(true);
  } else {
      m_jTax.setVisible(false);
      m_jaddtax.setVisible(false);
  }
  
  m_Ordersbag.activate();  
  customerNavigator.loadData();
}

@Override
public boolean deactivate() {

  return m_Ordersbag.deactivate();
}

@Override
public I_DataLogicCustomers getDlCustomers() {
  return this.dlCustomers;
}

@Override
public I_DataLogicERP getDlSales() {
  return this.dlSales;
}


public javax.swing.JPanel getM_jPanelBag() {
	return m_jPanelBag;
}

protected abstract void printPartialTotals();
protected abstract JOrdersBag getJOrdersBag();
protected abstract Component getSouthComponentToolBar();
protected abstract Component getSouthComponent();
protected abstract void resetSouthComponent();

@Override
public void setActiveOrder(Order oOrder, Object oOrderExt,boolean editModel) {
  m_oOrder = oOrder;
  m_oOrderExt = oOrderExt;
  changeLineList.setSelected(false);
  if (m_oOrder != null) {
      buildOrderLinePanel();
      // Asign preeliminary properties to the receipt
      if(editModel){
         m_oOrder.setActiveCash(m_App.getSystemCashIndex());
      }
      executeEvent(orderManager, m_oOrderExt, "Order.show");
      try {
          orderManager.setOrder(oOrder, editModel);
      } catch (BasicException ex) {
          new MessageInf(ex).show(this);
      }
      refreshEditModel();
  }
  refreshOrder();
}

@Override
public Order getActiveOrder() {
  reflushOrder(m_oOrder);
  return m_oOrder;
}

public boolean isOrderEditable(){
	return orderManager.isEditAble();
}



@Override
public Order getReCalcActiveOrder() throws TaxesException, BasicException {
	reflushOrder(m_oOrder);
	reCalcOrder();
	return m_oOrder;
}

@Override
public String getTitle() {
	return null;
}

private void refreshOrder() {
  CardLayout cl = (CardLayout)(getLayout());
  if (m_oOrder == null) {
      m_jOrderId.setText(null);
      if(m_Orderlines!=null)
          m_Orderlines.clearOrderLines();

      jCurrPageIndex.setText(null);
  
      stateToZero();
      
      // Muestro el panel de nulos.
      cl.show(this, "null");  
      // resetSouthComponent();
  } else {
      // Refresh order taxes
      for (OrderLine line : orderManager.getLines()) {
          line.setTaxInfo(taxeslogic.getTaxInfo(line.getProductTaxCategoryID(), m_oOrder.getCustomer()));
      }  
  
      // The order name
      m_jOrderId.setText(m_oOrder.getOrderId());

      jCurrPageIndex.setText(String.valueOf(orderManager.getCurrentPage().getPageIndex()));
      // Limpiamos todas las filas y anadimos las del order actual
      m_Orderlines.clearOrderLines();

      for (int i = 0; i < orderManager.getLinesCount(); i++) {
          m_Orderlines.addOrderLine(orderManager.getLine(i));
      } 
      stateToZero();   
      // Muestro el panel de Orders.
      cl.show(this, "order");
      resetSouthComponent();
      printPartialTotals();
      // activo el tecleador...
      m_jKeyFactory.setText(null);       
      java.awt.EventQueue.invokeLater(new Runnable() {
          @Override
          public void run() {
              m_jKeyFactory.requestFocus();
          }
      });
  }
}
private void paintOrderLine(int index, OrderLine oLine,boolean updateColult){
  if (executeEventAndRefresh("Order.setline", new ScriptArg("index", index), new ScriptArg("line", oLine)) == null) {
      if(updateColult)
  	   try {
			   OrderUtil.updateOrderLineConsultMultiply(dlSales, m_oOrder, oLine);
		    } catch (BasicException e) {
			   Toolkit.getDefaultToolkit().beep();
             new MessageInf(MessageInf.SGN_NOTICE, AppLocal.getIntString("message.updateOrderLineConsultMultiplyError")).show(this);
             stateToZero(); 
             return;
		    }
      orderManager.setLine(index, oLine);
      m_Orderlines.setOrderLine(index, oLine);
      m_Orderlines.setSelectedIndex(index);
      printPartialTotals();   
      stateToZero();  
      // event receipt
      executeEventAndRefresh("Order.change");
  }
}

private void addOrderLine(Product oProduct, double dMul, double dPrice) {
  Tax tax = taxeslogic.getTaxInfo(oProduct.getTaxCategoryID(), m_oOrder.getCustomer());
  double consultPrice;
	try {
		consultPrice = OrderUtil.chioceConsultPrice(dlSales,m_oOrder, oProduct);
		addOrderLine(new OrderLine(oProduct, dMul, dPrice, tax, (java.util.HashMap) (oProduct.getProperties().clone()),1,consultPrice));
	} catch (BasicException e) {
		new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.getConsultProductPriceError"), e).show(this);
	}
}

protected void addOrderLine(OrderLine oLine) {
  if (executeEventAndRefresh("Order.addline", new ScriptArg("line", oLine)) == null) {
      OrderType oType = m_oOrder.getDefineType();
      if (!oType.orderLineAddAble(oLine.getLineStyle())) {
          return;
      }
      if (!orderLineExistCheck(oLine,true)) {
          if (oLine.isProductCom()) {
              // Comentario entonces donde se pueda
              int i = m_Orderlines.getSelectedIndex();

              // me salto el primer producto normal...
              if (i >= 0 && !orderManager.getLine(i).isProductCom()) {
                  i++;
              }
              // me salto todos los productos auxiliares...
              while (i >= 0 && i < orderManager.getLinesCount() && orderManager.getLine(i).isProductCom()) {
                  i++;
              }
              if (i >= 0) {
                  try {
						OrderUtil.updateOrderLineConsultMultiply(dlSales, m_oOrder, oLine);
						 orderManager.insertLine(i, oLine);
	                     m_Orderlines.insertOrderLine(i, oLine); // Pintamos la linea en la vista...
					} catch (BasicException e) {
						new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.updateOrderLineConsultMultiplyError"), e).show(this);
					}
              } else {
                  Toolkit.getDefaultToolkit().beep();
              }
          } else {
              // Producto normal, entonces al finalnewline.getMultiply()
              try {
					OrderUtil.updateOrderLineConsultMultiply(dlSales, m_oOrder, oLine);
					orderManager.addLine(oLine);
	                m_Orderlines.addOrderLine(oLine); // Pintamos la linea en la vista...
				} catch (BasicException e) {
					new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.updateOrderLineConsultMultiplyError"), e).show(this);
				}
             
          }
      }
      printPartialTotals();
      stateToZero();
      // event receipt
      executeEventAndRefresh("Order.change");
  }
}    

private boolean orderLineExistCheck(OrderLine oLine,boolean showMessage){
   OrderType oType = m_oOrder.getDefineType();
   boolean existed = false;
  if (oLine.getLineStyle() == OrderLine.PRODUCTLINE) {
          OrderLine inOrderLine = orderManager.getOrderLineByProductId(oLine.getProductID(),oLine.getProductAttSetInstId());
          if (oType.getOrderLineType() == OrderType.ORDERLINETYPE_SupportUniqueProduct || oType.getOrderLineType() == OrderType.ORDERLINETYPE_SupportUniqueProductAndService) {
              if (inOrderLine != null) {
                  existed = true;
                  if(showMessage){
                      Toolkit.getDefaultToolkit().beep();
                      new MessageInf(MessageInf.SGN_NOTICE, AppLocal.getIntString("message.alreadyexist")).show(this);
                 }
              }
          } else if (oType.getOrderLineType() == OrderType.ORDERLINETYPE_SupportUniqueProductAddAndService || oType.getOrderLineType() == OrderType.ORDERLINETYPE_SupportUniqueProductAdded) {
              if (inOrderLine != null) {
                  inOrderLine.setMultiply(inOrderLine.getMultiply() + oLine.getMultiply());
                  existed = true;
                  int index=orderManager.getOrderLineIndexInCurrentPage(inOrderLine);
                  if(index>=0)
                      paintOrderLine(index,inOrderLine,false);
                  if(showMessage){
                     Toolkit.getDefaultToolkit().beep();
                     new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.alreadyexistandadded")).show(this);
                  }
              }
          }
      }
   return existed;
}

private void removeOrderLine(int i){  
  if (executeEventAndRefresh("Order.removeline", new ScriptArg("index", i)) == null) {
  
      if (orderManager.getLine(i).isProductCom()) {
          // Es un producto auxiliar, lo borro y santas pascuas.
          orderManager.removeLine(i);
          m_Orderlines.removeOrderLine(i);
      } else {
          // Es un producto normal, lo borro.
          orderManager.removeLine(i);
          m_Orderlines.removeOrderLine(i);
          // Y todos lo auxiliaries que hubiera debajo.
          while(i < orderManager.getLinesCount() && orderManager.getLine(i).isProductCom()) {
              orderManager.removeLine(i);
              m_Orderlines.removeOrderLine(i);
          }
      }
      
      printPartialTotals(); // pinto los totales parciales...                           
      stateToZero(); // Pongo a cero    

      // event receipt
      executeEventAndRefresh("Order.change");
  }
}

private Product getInputProduct() {
  Product oProduct = new Product(); // Es un order
  oProduct.setReference(null);
  oProduct.setCode(null);
  oProduct.setName("");
  oProduct.setTaxCategoryID(((TaxCategory) taxcategoriesmodel.getSelectedItem()).getID());
  OrderType type=m_oOrder.getDefineType();
  oProduct.setPriceSell(includeTaxes(oProduct.getTaxCategoryID(), getInputValue()));
  return oProduct;
}


private double includeTaxes(String tcid, double dValue) {
  if (m_jaddtax.isSelected()) {
      Tax tax = taxeslogic.getTaxInfo(tcid, m_oOrder.getCustomer());
      double dTaxRate = tax == null ? 0.0 : tax.getRate();           
      return dValue / (1.0 + dTaxRate);      
  } else {
      return dValue;
  }
}

private double getInputValue() {
  try {
      return Double.parseDouble(m_jPrice.getText());
  } catch (NumberFormatException e){
      return 0.0;
  }
}

private double getPorValue() {
  try {
      return Double.parseDouble(m_jPor.getText().substring(1));                
  } catch (NumberFormatException e){
      return 1.0;
  } catch (StringIndexOutOfBoundsException e){
      return 1.0;
  }
}

private void stateToZero(){
  m_jPor.setText("");
  m_jPrice.setText("");

  m_iNumberStatus = NUMBER_INPUTZERO;
  m_iNumberStatusInput = NUMBERZERO;
  m_iNumberStatusPor = NUMBERZERO;
}

private void incProductByCode(String sCode) {
  if(sCode.isEmpty()){
     stateToZero();
     return ;
  }
  boolean isSeachModel=false;
  // precondicion: sCode != null
  sCode.toUpperCase();
  try {
      Product oProduct=null;
      if(sCode.startsWith("~")){
      	isSeachModel=true;
            java.util.List<Product> prods=dlSales.listProductByMnemonic(sCode.substring(1));
            if(prods!=null&&prods.size()>0)
                if(prods.size()==1)
                   oProduct=prods.get(0);
                else
                   oProduct=getProductFinder().setProductList(prods);
      }else{
          oProduct = ProductSwingUtil.getProductInfo(this, dlSales, sCode.trim());
      }
      if (oProduct == null) {                  
          Toolkit.getDefaultToolkit().beep(); 
          stateToZero();
          if(!isSeachModel&&security.hasPermissionByName(ERPPermission.COMMERCIALOBJECT_Product)){
            int res = JOptionPane.showConfirmDialog(this, AppLocal.getIntString("message.noproductthenadded"), AppLocal.getIntString("title.editor"), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
            if (res == JOptionPane.YES_OPTION) {
                 addNewProduct(sCode);
             }
          }else 
          	new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.noproduct")).show(this);
      } else {
          // Se anade directamente una unidad con el precio y todo
          incProduct(oProduct);
      }
  } catch (BasicException eData) {
      stateToZero();           
      new MessageInf(eData).show(this);           
  }
}

private void incProductByCodePrice(String sCode, double dPriceSell) {
 if(sCode.isEmpty()){
     stateToZero();
     return ;
  }
// precondicion: sCode != null
      Product oProduct = ProductSwingUtil.getProductInfo(this,dlSales,  sCode);
      if (oProduct == null) {                  
         Toolkit.getDefaultToolkit().beep();
         stateToZero();
         if(security.hasPermissionByName(ERPPermission.COMMERCIALOBJECT_Product)){
             int res = JOptionPane.showConfirmDialog(this, AppLocal.getIntString("message.noproductthenadded"), AppLocal.getIntString("title.editor"), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
             if (res == JOptionPane.YES_OPTION) {
                  addNewProduct(sCode);
              }
          }
      } else {
          // Se anade directamente una unidad con el precio y todo
          if (m_jaddtax.isSelected()) {
              // debemos quitarle los impuestos ya que el precio es con iva incluido...
              Tax tax = taxeslogic.getTaxInfo(oProduct.getTaxCategoryID(), m_oOrder.getCustomer());
              addOrderLine(oProduct, 1.0, dPriceSell / (1.0 + tax.getRate()));
          } else {
              addOrderLine(oProduct, 1.0, dPriceSell);
          }                
      }
}

private void incProduct(Product prod) {
  if (prod.isScale() && m_App.getDeviceScale().existsScale()) {
      try {
          Double value = m_App.getDeviceScale().readWeight();
          if (value != null) {
              incProduct(value.doubleValue(), prod);
          }
      } catch (ScaleException e) {
          Toolkit.getDefaultToolkit().beep();                
          new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.noweight"), e).show(this);           
          stateToZero(); 
      }
  } else {
      // No es un producto que se pese o no hay balanza
      incProduct(1.0, prod);
  }
}

public  boolean incOutProduct(String sCode, double unit, double dPrice){
  if(sCode.isEmpty())
     return false;
  try {
      Product oProduct = ProductSwingUtil.getProductInfo(this, dlSales, sCode);
      if (oProduct == null) {
          return false;
      } else {
          if(dPrice==0)
              dPrice=OrderUtil.chiocePrice(dlSales,m_oOrder,oProduct);
          // Se anade directamente una unidad con el precio y todo
          if (m_jaddtax.isSelected()) {
              // debemos quitarle los impuestos ya que el precio es con iva incluido...
              Tax tax = taxeslogic.getTaxInfo(oProduct.getTaxCategoryID(), m_oOrder.getCustomer());
              addOrderLine(oProduct, unit, dPrice / (1.0 + tax.getRate()));
          } else {
              addOrderLine(oProduct, unit, dPrice);
          }
      }
  } catch (BasicException eData) {
     return false;
  }
  return true;
}


private void incProduct(double dPor, Product prod) {
  // precondicion: prod != null
	Double price;
	try {
		price = OrderUtil.chiocePrice(dlSales,m_oOrder,prod);
		addOrderLine(prod, dPor, price);
	} catch (BasicException e) {
		 new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.getProductPriceError"), e).show(this);
	}
}
 
protected void buttonTransition(Product prod) {
// precondicion: prod != null 
   if (m_iNumberStatusInput == NUMBERZERO && m_iNumberStatusPor == NUMBERZERO) {
      incProduct(prod);
  } else if (m_iNumberStatusInput == NUMBERVALID && m_iNumberStatusPor == NUMBERZERO) {
      incProduct(getInputValue(), prod);
  } else {
      Toolkit.getDefaultToolkit().beep();
  }       
}

private void stateTransition(char cTrans) {
   if(!isEditAble())
       return;
  String m_sBarcode=m_jPrice.getText();
  if (cTrans == '\n') {
      // Codigo de barras introducido
      if (m_sBarcode!=null&&m_sBarcode.length() > 0) {            
          String sCode = m_sBarcode;
          if (sCode.startsWith("c")) {
              // barcode of a customers card
              try {
                  BusinessPartner newcustomer = dlSales.findCustomerByCard(sCode);
                  if (newcustomer == null) {
                      Toolkit.getDefaultToolkit().beep();                   
                      new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.nocustomer")).show(this);           
                  } else {
                      m_oOrder.setCustomer(newcustomer);
                      m_jOrderId.setText(m_oOrder.getOrderId());
                  }
              } catch (BasicException e) {
                  Toolkit.getDefaultToolkit().beep();                   
                  new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.nocustomer"), e).show(this);           
              }
              stateToZero();
          } else if (sCode.length() == 13 && sCode.startsWith("250")) {
              // barcode of the other machine
              Product oProduct = new Product(); // Es un order
              oProduct.setReference(null); // para que no se grabe
              oProduct.setCode(sCode);
              oProduct.setName("Order " + sCode.substring(3, 7));
              oProduct.setPriceSell(Double.parseDouble(sCode.substring(7, 12)) / 100);   
              oProduct.setTaxCategoryID(((TaxCategory) taxcategoriesmodel.getSelectedItem()).getID());
              // Se anade directamente una unidad con el precio y todo
              addOrderLine(oProduct, 1.0, includeTaxes(oProduct.getTaxCategoryID(),oProduct.getPriceSell()));
          } else if (sCode.length() == 13 && sCode.startsWith("210")) {
              // barcode of a weigth product
              incProductByCodePrice(sCode.substring(0, 7), Double.parseDouble(sCode.substring(7, 12)) / 100);
          } else {
              incProductByCode(sCode);
          }
      } else {
          Toolkit.getDefaultToolkit().beep();
      }
  } else {
      // otro caracter
      // Esto es para el codigo de barras...
      //m_sBarcode.append(cTrans);

      // Esto es para el los productos normales...
      if (cTrans == '\u007f') { 
          stateToZero();
      }else if ((cTrans == '~'||cTrans == '～')&& (m_iNumberStatus == NUMBER_INPUTZERO)) {
           m_jPrice.setText("~");
           m_iNumberStatus = NUMBER_INPUTINT;    
           m_iNumberStatusInput = NUMBERVALID;
      } else if(m_jPrice!=null&&(m_iNumberStatus == NUMBER_INPUTINT)&&m_jPrice.getText().startsWith("~")){
      	 m_jPrice.setText(m_jPrice.getText() + cTrans);
      } else if ((cTrans == 'c')  && (m_iNumberStatus == NUMBER_INPUTZERO)) {
          m_jPrice.setText("c"); 
          m_iNumberStatus = NUMBER_INPUTINT;    
          m_iNumberStatusInput = NUMBERVALID;
      }/**else if ((cTrans == '0') 
              && (m_iNumberStatus == NUMBER_INPUTZERO)) {
          m_jPrice.setText("0");            
      }**/
      else if ((cTrans == '0' || cTrans == '1' || cTrans == '2' || cTrans == '3' || cTrans == '4' || cTrans == '5' || cTrans == '6' || cTrans == '7' || cTrans == '8' || cTrans == '9')
              && (m_iNumberStatus == NUMBER_INPUTZERO)) { 
          // Un numero entero
          m_jPrice.setText(Character.toString(cTrans));
          m_iNumberStatus = NUMBER_INPUTINT;    
          m_iNumberStatusInput = NUMBERVALID;
      } else if ((cTrans == '0' || cTrans == '1' || cTrans == '2' || cTrans == '3' || cTrans == '4' || cTrans == '5' || cTrans == '6' || cTrans == '7' || cTrans == '8' || cTrans == '9')
                 && (m_iNumberStatus == NUMBER_INPUTINT)) { 
          // Un numero entero
          m_jPrice.setText(m_jPrice.getText() + cTrans);
      } else if(String.valueOf(cTrans).matches("[A-Z|a-z]")&&(m_iNumberStatus == NUMBER_INPUTZERO || m_iNumberStatus == NUMBER_INPUTINT)){
      	m_jPrice.setText(m_jPrice.getText() + cTrans);
      } else if (cTrans == '.' && m_iNumberStatus == NUMBER_INPUTZERO) {
          m_jPrice.setText("0.");
          m_iNumberStatus = NUMBER_INPUTZERODEC;            
      } else if (cTrans == '.' && m_iNumberStatus == NUMBER_INPUTINT) {
          m_jPrice.setText(m_jPrice.getText() + ".");
          m_iNumberStatus = NUMBER_INPUTDEC;
      } else if ((cTrans == '0')
                 && (m_iNumberStatus == NUMBER_INPUTZERODEC || m_iNumberStatus == NUMBER_INPUTDEC)) { 
          // Un numero decimal
          m_jPrice.setText(m_jPrice.getText() + cTrans);
      } else if ((cTrans == '1' || cTrans == '2' || cTrans == '3' || cTrans == '4' || cTrans == '5' || cTrans == '6' || cTrans == '7' || cTrans == '8' || cTrans == '9')
                 && (m_iNumberStatus == NUMBER_INPUTZERODEC || m_iNumberStatus == NUMBER_INPUTDEC)) { 
          // Un numero decimal
          m_jPrice.setText(m_jPrice.getText() + cTrans);
          m_iNumberStatus = NUMBER_INPUTDEC;
          m_iNumberStatusInput = NUMBERVALID;
      } else if (cTrans == '*' 
              && (m_iNumberStatus == NUMBER_INPUTINT || m_iNumberStatus == NUMBER_INPUTDEC)) {
          m_jPor.setText("x");
          m_iNumberStatus = NUMBER_PORZERO;            
      } else if (cTrans == '*' 
              && (m_iNumberStatus == NUMBER_INPUTZERO || m_iNumberStatus == NUMBER_INPUTZERODEC)) {
          m_jPrice.setText("0");
          m_jPor.setText("x");
          m_iNumberStatus = NUMBER_PORZERO;       

      } else if ((cTrans == '0') 
              && (m_iNumberStatus == NUMBER_PORZERO)) {
          m_jPor.setText("x0");            
      } else if ((cTrans == '1' || cTrans == '2' || cTrans == '3' || cTrans == '4' || cTrans == '5' || cTrans == '6' || cTrans == '7' || cTrans == '8' || cTrans == '9')
              && (m_iNumberStatus == NUMBER_PORZERO)) { 
          // Un numero entero
          m_jPor.setText("x" + Character.toString(cTrans));
          m_iNumberStatus = NUMBER_PORINT;            
          m_iNumberStatusPor = NUMBERVALID;
      } else if ((cTrans == '0' || cTrans == '1' || cTrans == '2' || cTrans == '3' || cTrans == '4' || cTrans == '5' || cTrans == '6' || cTrans == '7' || cTrans == '8' || cTrans == '9')
                 && (m_iNumberStatus == NUMBER_PORINT)) { 
          // Un numero entero
          m_jPor.setText(m_jPor.getText() + cTrans);

      } else if (cTrans == '.' && m_iNumberStatus == NUMBER_PORZERO) {
          m_jPor.setText("x0.");
          m_iNumberStatus = NUMBER_PORZERODEC;            
      } else if (cTrans == '.' && m_iNumberStatus == NUMBER_PORINT) {
          m_jPor.setText(m_jPor.getText() + ".");
          m_iNumberStatus = NUMBER_PORDEC;

      } else if ((cTrans == '0')
                 && (m_iNumberStatus == NUMBER_PORZERODEC || m_iNumberStatus == NUMBER_PORDEC)) { 
          // Un numero decimal
          m_jPor.setText(m_jPor.getText() + cTrans);
      } else if ((cTrans == '1' || cTrans == '2' || cTrans == '3' || cTrans == '4' || cTrans == '5' || cTrans == '6' || cTrans == '7' || cTrans == '8' || cTrans == '9')
                 && (m_iNumberStatus == NUMBER_PORZERODEC || m_iNumberStatus == NUMBER_PORDEC)) { 
          // Un numero decimal
          m_jPor.setText(m_jPor.getText() + cTrans);
          m_iNumberStatus = NUMBER_PORDEC;            
          m_iNumberStatusPor = NUMBERVALID;  
      
      }  else if (cTrans == '\u00a7'
              && m_iNumberStatusInput == NUMBERVALID && m_iNumberStatusPor == NUMBERZERO) {
          // Scale button pressed and a number typed as a price
          if (m_App.getDeviceScale().existsScale()) {
              try {
                  Double value = m_App.getDeviceScale().readWeight();
                  if (value != null) {
                      Product product = getInputProduct();
                      addOrderLine(product, value.doubleValue(), product.getPriceSell());
                  }
              } catch (ScaleException e) {
                  Toolkit.getDefaultToolkit().beep();
                  new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.noweight"), e).show(this);           
                  stateToZero(); 
              }
          } else {
              // No existe la balanza;
              Toolkit.getDefaultToolkit().beep();
          }
      } else if (cTrans == '\u00a7' 
              && m_iNumberStatusInput == NUMBERZERO && m_iNumberStatusPor == NUMBERZERO) {
          // Scale button pressed and no number typed.
          int i = m_Orderlines.getSelectedIndex();
          if (i < 0){
              Toolkit.getDefaultToolkit().beep();
          } else if (m_App.getDeviceScale().existsScale()) {
              try {
                  Double value = m_App.getDeviceScale().readWeight();
                  if (value != null) {
                      OrderLine newline = orderManager.getLine(i).copyOrderLine();
                      newline.setMultiply(value.doubleValue());
                      
                      newline.setPrice(Math.abs(newline.getPrice()));
                      paintOrderLine(i, newline,false);
                  }
              } catch (ScaleException e) {
                  // Error de pesada.
                  Toolkit.getDefaultToolkit().beep();
                  new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.noweight"), e).show(this);           
                  stateToZero(); 
              }
          } else {
              // No existe la balanza;
              Toolkit.getDefaultToolkit().beep();
          }      
          
      // Add one product more to the selected line
      } else if (cTrans == '+' 
              && m_iNumberStatusInput == NUMBERZERO && m_iNumberStatusPor == NUMBERZERO) {
          int i = m_Orderlines.getSelectedIndex();
          if (i < 0){
              Toolkit.getDefaultToolkit().beep();
          } else {
              OrderLine newline = orderManager.getLine(i).copyOrderLine();
              //If it's a refund + button means one unit less
              if (m_oOrder.getOrderType() == Order.ORDERBEARING_REVERSE){
                  newline.setMultiply(newline.getMultiply() - 1.0);
                  paintOrderLine(i, newline,false);
              }
              else {
                  // add one unit to the selected line
                  newline.setMultiply(newline.getMultiply() + 1.0);
                  paintOrderLine(i, newline,false);
              }
          }

      // Delete one product of the selected line
      } else if (cTrans == '-' 
              && m_iNumberStatusInput == NUMBERZERO && m_iNumberStatusPor == NUMBERZERO) {
          
          int i = m_Orderlines.getSelectedIndex();
          if (i < 0){
              Toolkit.getDefaultToolkit().beep();
          } else {
              OrderLine newline = orderManager.getLine(i).copyOrderLine();
              //If it's a refund - button means one unit more
              if (m_oOrder.getOrderType() == Order.ORDERBEARING_REVERSE){
                  newline.setMultiply(newline.getMultiply() + 1.0);
                  if (newline.getMultiply() >= 0) {
                      removeOrderLine(i);
                  } else {
                      paintOrderLine(i, newline,false);
                  }
              } else {
                  // substract one unit to the selected line
                  newline.setMultiply(newline.getMultiply() - 1.0);
                  if (newline.getMultiply() <= 0.0) {                   
                      removeOrderLine(i); // elimino la linea
                  } else {
                      paintOrderLine(i, newline,false);
                  }
              }
          }

      // Set n products to the selected line
      } else if (cTrans == '+' 
              && m_iNumberStatusInput == NUMBERZERO && m_iNumberStatusPor == NUMBERVALID) {
          int i = m_Orderlines.getSelectedIndex();
          if (i < 0){
              Toolkit.getDefaultToolkit().beep();
          } else {
              double dPor = getPorValue();
              OrderLine newline = orderManager.getLine(i).copyOrderLine();
              if (m_oOrder.getOrderType() == Order.ORDERBEARING_REVERSE) {
                  newline.setMultiply(-dPor);

                   newline.setPrice(Math.abs(newline.getPrice()));
                  paintOrderLine(i, newline,false);
              } else {
                  newline.setMultiply(dPor);

                  newline.setPrice(Math.abs(newline.getPrice()));
                  paintOrderLine(i, newline,false);
              }
          }

      // Set n negative products to the selected line
      } else if (cTrans == '-' 
              && m_iNumberStatusInput == NUMBERZERO && m_iNumberStatusPor == NUMBERVALID) {
          
          int i = m_Orderlines.getSelectedIndex();
          if (i < 0){
              Toolkit.getDefaultToolkit().beep();
          } else {
              double dPor = getPorValue();
              OrderLine newline = orderManager.getLine(i).copyOrderLine();
              if (m_oOrder.getOrderType() == Order.ORDERBEARING_NORMAL) {
                  newline.setMultiply(dPor);

                  newline.setPrice(-Math.abs(newline.getPrice()));
                  paintOrderLine(i, newline,false);
              }           
          }

      // Anadimos 1 producto
      } else if (cTrans == '+' 
              && m_iNumberStatusInput == NUMBERVALID && m_iNumberStatusPor == NUMBERZERO) {
          Product product = getInputProduct();
          addOrderLine(product, 1.0, product.getPriceSell());
          
      // Anadimos 1 producto con precio negativo
      } else if (cTrans == '-' 
              && m_iNumberStatusInput == NUMBERVALID && m_iNumberStatusPor == NUMBERZERO) {
          Product product = getInputProduct();
          addOrderLine(product, 1.0, -product.getPriceSell());

      // Anadimos n productos
      } else if (cTrans == '+' 
              && m_iNumberStatusInput == NUMBERVALID && m_iNumberStatusPor == NUMBERVALID) {
          Product product = getInputProduct();
          addOrderLine(product, getPorValue(),product.getPriceSell());

      // Anadimos n productos con precio negativo ?
      } else if (cTrans == '-'
              && m_iNumberStatusInput == NUMBERVALID && m_iNumberStatusPor == NUMBERVALID) {
          Product product = getInputProduct();
          addOrderLine(product, getPorValue(), product.getPriceSell());

      // Totals() Igual;
      } else if (cTrans == ' ' || cTrans == '=') {
          if (orderManager.getOrderLinesCount()> 0) {
              paymentOrder(m_oOrder, m_oOrderExt);
          } else {
              Toolkit.getDefaultToolkit().beep();
          }
      }
  }
}


private void paymentOrder(Order order, Object orderext){
  if(!isEditAble())
      return;
  try { 
	  order.resetTaxes();
	  order.resetPayments();
      getReCalcActiveOrder();
  } catch (TaxesException e) {
      MessageInf msg = new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.cannotcalculatetaxes"));
      msg.show(this);
  } catch (BasicException e) {
  	 new MessageInf(MessageInf.SGN_WARNING, e.getMessage()).show(this);
	}
  if (OrderType.FUNDTYPE_NoChange == order.getDefineType().getFundType()) {
      return;
  }
  
  if (executeEvent(orderManager, orderext, "Order.total") == null) {
      	JPaymentSelect paydialog = this.paymentdialog;
          paydialog.setPrintSelected(false);
          paydialog.setTransactionID(OrderHelper.getTransactionID(order));
          if (paydialog.showDialog(order.getTotalPrice(), order.getCustomer())) {
              // assign the payments selected and calculate taxes.
          	
          	java.util.List<PaymentInfo> payments=paydialog.getSelectedPayments();
          	orderManager.setPayments(payments);
          }
      } 
  
}

public void reCalcOrder() throws TaxesException, BasicException {
	OrderUtil.reCalcOrder(m_oOrder, orderCalcManager, taxeslogic);
}

private boolean closeOrder(Order order, String memo) {
  boolean resultok = false;
  if (executeEvent(orderManager, memo, "Order.save") == null) {
      // Save the receipt and assign a receipt number
  	OrderState endState = null;
      try {
      	endState=new OrderState(m_App.getAppUserView().getUser().getUserInfo(),AppLocal.getIntString(OrderState.ORDERSTATE_End),memo);
          order.addState(endState);
          dlSales.saveOrder(order);
          m_Ordersbag.flushOrder(); 
      } catch (BasicException eData) {
          MessageInf msg = new MessageInf(MessageInf.SGN_NOTICE, AppLocal.getIntString("message.nosaveOrder"), eData);
          msg.show(this);
          order.getStates().remove(endState);
          return false;
      }
      return true;
  }

  // cancelled the order.total script
  // or canceled the payment dialog
  // or canceled the order.close script
  return resultok;
}

private void printReport(String resourcefile, Order order, Object Orderext) {
  try {     
  	  OrderUtil.reCalcOrder(order, orderCalcManager, taxeslogic);
      JasperReport jr; 
      InputStream in = getClass().getResourceAsStream(resourcefile + ".ser");
      if (in == null) {      
          // read and compile the report
          JasperDesign jd = JRXmlLoader.load(getClass().getResourceAsStream("/cn/ekuma/reports/order/"+resourcefile + ".jrxml"));
          jr = JasperCompileManager.compileReport(jd);    
      } else {
          // read the compiled reporte
          ObjectInputStream oin = new ObjectInputStream(in);
          jr = (JasperReport) oin.readObject();
          oin.close();
      }
     
      // Construyo el mapa de los parametros.
      Map reportparams = new HashMap();
      // reportparams.put("ARG", params);
      try {
          reportparams.put("REPORT_RESOURCE_BUNDLE", ResourceBundle.getBundle("cn/ekuma/reports/order/"+resourcefile));
      } catch (MissingResourceException e) {
      }
      reportparams.put("TAXESLOGIC", taxeslogic); 
      reportparams.put("ORDER_ID", order.getOrderId());
      if(Order.ORDERBEARING_REVERSE == order.getOrderType())
          reportparams.put("ORDER_NAME",order.getDefineType().getReverseName());
      else
          reportparams.put("ORDER_NAME",order.getDefineType().getName());   
      reportparams.put("ORDER_CURDATE", OrderHelper.printDate(order));
      reportparams.put("ORDER_CUSTOMER", OrderHelper.printCustomerAndAddr(order));
      reportparams.put("ORDER_CUSTOMER_ADDR",order.getCustomerAddr());
      reportparams.put("ORDER_LOCATION", order.getLocationDesc());
      reportparams.put("ORDER_LOCATION1", order.getLocationDesc1());
      reportparams.put("ORDER_USER", OrderHelper.printUser(order));
      reportparams.put("ORDER_ATTINSTDEC", order.getOrderAttSetInstDesc());
      reportparams.put("ORDER_ARTICLESCOUNT", OrderHelper.printArticlesCount(order));
      reportparams.put("ORDER_TAX", Formats.CURRENCY.formatValue(order.getTotalTax()));
      reportparams.put("ORDER_TOTAL",Formats.CURRENCY.formatValue(order.getTotalPrice()));
      reportparams.put("ORDER_TOTALPAID", OrderHelper.printTotalPaid(order));
      reportparams.put("ORDER_MEMO", order.getMemo());
      reportparams.put("ORDER_REFUSER", OrderHelper.printRefUser(order));
      reportparams.put("ORDER_DELIVERTYPE", order.getDeliverType());
      reportparams.put("ORDER_DELIVERTYPEDESC", order.getDeliverTypeDesc());
      reportparams.put("ORDER_TOTALRMB", MoneyUtil.uppercaseFullFromatRMB(order.getTotalPrice()));

     java.util.List<OrderLine_P> reportLines=new ArrayList();
      for(OrderLine line:order.getLines())
          reportLines.add(new OrderLine_P(line));
      JasperPrint jp = JasperFillManager.fillReport(jr, reportparams,new JRBeanCollectionDataSource(reportLines));

      JReportDialog.showReport(this,jp);

      
      //PrintService service = ReportUtils.getPrintService(m_App.getProperties().getProperty("machine.printername"));
      //JRPrinterAWT300.printPages(jp, 0, jp.getPages().size() - 1, service);
      
  } catch (Exception e) {
      MessageInf msg = new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.cannotloadreport"), e);
      msg.show(this);
  }               
}   


private Object evalScript(ScriptObject scr, String resource, ScriptArg... args) {
  
  // resource here is guaratied to be not null
   try {
      scr.setSelectedIndex(m_Orderlines.getSelectedIndex());
      return scr.evalScript(dlSystem.getResourceAsXML(resource), args);                
  } catch (ScriptException e) {
      MessageInf msg = new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.cannotexecute"), e);
      msg.show(this);
      return msg;
  } 
}
  
public void evalScriptAndRefresh(String resource, ScriptArg... args) {

  if (resource == null) {
      MessageInf msg = new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.cannotexecute"));
      msg.show(this);            
  } else {
      ScriptObject scr = new ScriptObject(orderManager, m_oOrderExt);
      scr.setSelectedIndex(m_Orderlines.getSelectedIndex());
      evalScript(scr, resource, args);   
      refreshOrder();
      setSelectedIndex(scr.getSelectedIndex());
  }
}  


private Object executeEventAndRefresh(String eventkey, ScriptArg ... args) {
  
  //String resource = m_jbtnconfig.getEvent(eventkey);
  String resource=null;
  if (resource == null) {
      return null;
  } else {
      ScriptObject scr = new ScriptObject(orderManager, m_oOrderExt);
      scr.setSelectedIndex(m_Orderlines.getSelectedIndex());
      Object result = evalScript(scr, resource, args);   
      refreshOrder();
      setSelectedIndex(scr.getSelectedIndex());
      return result;
  }
}

private Object executeEvent(OrderManager orderManager, Object Orderext, String eventkey, ScriptArg ... args) {
  
  //String resource = m_jbtnconfig.getEvent(eventkey);
  String resource=null;
  if (resource == null) {
      return null;
  } else {
      ScriptObject scr = new ScriptObject(orderManager, Orderext);
      return evalScript(scr, resource, args);
  }
}

public String getResourceAsXML(String sresourcename) {
  return dlSystem.getResourceAsXML(sresourcename);
}

public BufferedImage getResourceAsImage(String sresourcename) {
  return DataLogicSystemHelper.getResourceAsImage(dlSystem,sresourcename);
}

private void setSelectedIndex(int i) {
  
  if (i >= 0 && i < orderManager.getLinesCount()) {
      m_Orderlines.setSelectedIndex(i);
  } else if (orderManager.getLinesCount() > 0) {
      m_Orderlines.setSelectedIndex(orderManager.getLinesCount() - 1);
  }    
}

private void reflushOrder(Order order) {
  if(orderManager!=null){
    order.setLines(orderManager.buildOrderLines());
  }
}



private void refreshEditModel() {
	    boolean enable=isEditAble();
      btnCustomer.setEnabled(enable);
      jTxtImport.setEnabled(enable);
      m_jTax.setEnabled(enable);
      m_jaddtax.setEnabled(enable);
      changeLineList.setEnabled(enable);
}

void refulshCoult() {
  if(m_oOrder!=null&&m_oOrder.getDefineType().isConsult()){
     if(m_oOrder.getDefineType().getConsultType()==OrderType.CONSULTTYPE_Order&&m_oOrder.getConsultRef()==null)
  		return;
     for(OrderLine l:orderManager.buildOrderLines()){
        try {
			OrderUtil.updateOrderLineConsultMultiply(dlSales, m_oOrder, l);
		} catch (BasicException e) {
			new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.updateOrderLineConsultMultiplyError"), e).show(this);
		}
     }
     refreshOrder();
  }
}

void importConsult() {
  if(m_oOrder!=null&&m_oOrder.getDefineType().isConsult()){
  	if(m_oOrder.getDefineType().getConsultType()==OrderType.CONSULTTYPE_Order&&m_oOrder.getConsultRef()==null)
  		return;
      int consultType=m_oOrder.getDefineType().getConsultType();
      String consultID=m_oOrder.getConsultRef();
      java.util.List<OrderLineConsultInfo> list=null;
      try {
      if(consultType==OrderType.CONSULTTYPE_Order)
            list = dlSales.listConsultInfoByOrder(consultID);
      else if(consultType==OrderType.CONSULTTYPE_RealStore){
          if(m_oOrder.getCustomerId()==null)
              list=dlSales.listConsultInfoByRealStore(m_oOrder.getLocationRef());
          else
              list=dlSales.listConsultInfoByRealStore(m_oOrder.getLocationRef(),m_oOrder.getCustomerId());
      }
      else if(consultType==OrderType.CONSULTTYPE_TimeSliceStore)
           list=dlSales.listConsultInfoByTimeStore(consultID);
      } catch (BasicException ex) {
           MessageInf msg = new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.cannotexecute"));
           msg.show(this);
           return;
      }
      java.util.List<OrderLine> addLine=new ArrayList();
      for(OrderLineConsultInfo l:list){
          if(orderManager.getOrderLineByProductId(l.getProductID(),l.getAttributesetid())==null){
              OrderLine retLine = buildConsultOrderLine(l);
              if(retLine!=null){
                  addLine.add(retLine);
              }
          }
      }
      orderManager.addLines(addLine);
  }
}

private OrderLine buildConsultOrderLine(OrderLineConsultInfo l){
      OrderLine retLine = null;
      Product oProduct=null;
		try {
			oProduct = dlSales.getProductInfo(l.getProductID());
		} catch (BasicException e) {
			new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.noproduct")).show(this);
			return null;
		}
      if (oProduct != null) {
          double dPrice;
			try {
				dPrice = OrderUtil.chiocePrice(dlSales,m_oOrder, oProduct);
			} catch (BasicException e) {
				 new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.getProductPriceError"), e).show(this);
				 return null;
			}
          // Se anade directamente una unidad con el precio y todo
          Tax tax =null;
          if (m_jaddtax.isSelected()) {
              // debemos quitarle los impuestos ya que el precio es con iva incluido...
              tax = taxeslogic.getTaxInfo(oProduct.getTaxCategoryID(), m_oOrder.getCustomer());
          }
         double consultPrice;
		try {
			consultPrice = OrderUtil.chioceConsultPrice(dlSales,m_oOrder, oProduct);
		} catch (BasicException e) {
			new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.getConsultProductPriceError"), e).show(this);
			return null;
		}
         retLine= new OrderLine(oProduct, 0, dPrice, tax, (java.util.HashMap) (oProduct.getProperties().clone()),1,consultPrice);
         retLine.setConsulMultiply(l.getMultiply());
         retLine.setProductAttSetInstId(l.getAttributesetid());
      }
  
  return retLine;
}

public class ScriptObject {
  
  private OrderManager orderManager;
  private Object orderext;
  
  private int selectedindex;
  
  private ScriptObject(OrderManager orderManager, Object orderext) {
      this.orderManager = orderManager;
      this.orderext = orderext;
  }
  
  public double getInputValue() {
      if (m_iNumberStatusInput == NUMBERVALID && m_iNumberStatusPor == NUMBERZERO) {
          return JPanelOrder.this.getInputValue();
      } else {
          return 0.0;
      }
  }
  
  public int getSelectedIndex() {
      return selectedindex;
  }
  
  public void setSelectedIndex(int i) {
      selectedindex = i;
  }  
  
  public void printReport(String resourcefile) {
      JPanelOrder.this.printReport(resourcefile, orderManager.getOrder(), orderext);
  }
  
  public void print(String sresourcename) {
      //JPanelOrder.this.printOrder(sresourcename, orderManager.getOrder(), orderext);
  }              
  
  public Object evalScript(String code, ScriptArg... args) throws ScriptException {
      
      ScriptEngine script = ScriptFactory.getScriptEngine(ScriptFactory.BEANSHELL);
      script.put("OrderManager", orderManager);
      script.put("place", orderext);
      script.put("taxes", taxcollection);
      script.put("taxeslogic", taxeslogic);             
      script.put("user", m_App.getAppUserView().getUser());
      script.put("sales", this);

      // more arguments
      for(ScriptArg arg : args) {
          script.put(arg.getKey(), arg.getValue());
      }             

      return script.eval(code);
  }            
}

/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the FormEditor.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {

  m_jPanContainer = new javax.swing.JPanel();
  m_jOptions = new javax.swing.JPanel();
  m_jButtons = new javax.swing.JPanel();
  m_jOrderId = new javax.swing.JLabel();
  btnCustomer = new javax.swing.JButton();
  jOrderAttr = new javax.swing.JButton();
  jTxtImport = new javax.swing.JButton();
  jPanel3 = new javax.swing.JPanel();
  jFirstPage = new javax.swing.JButton();
  jBeforePage = new javax.swing.JButton();
  jCurrPageIndex = new javax.swing.JButton();
  jNextPage = new javax.swing.JButton();
  jLastPage = new javax.swing.JButton();
  m_jPanelScripts = new javax.swing.JPanel();
  m_jButtonsExt = new javax.swing.JPanel();
  jPrintTempPanel = new javax.swing.JPanel();
  jReportCombo = new javax.swing.JComboBox();
  jButton1 = new javax.swing.JButton();
  m_jPanelBag = new javax.swing.JPanel();
  m_jContEntries = new javax.swing.JPanel();
  container = new javax.swing.JPanel();
  jPanel6 = new javax.swing.JPanel();
  containerToolbar = new javax.swing.JPanel();
  jPanel1 = new javax.swing.JPanel();
  m_jPrice = new javax.swing.JLabel();
  m_jTax = new javax.swing.JComboBox();
  m_jaddtax = new javax.swing.JToggleButton();
  m_jPor = new javax.swing.JLabel();

  setBackground(new java.awt.Color(255, 204, 153));
  setLayout(new java.awt.CardLayout());

  m_jPanContainer.setLayout(new java.awt.BorderLayout());

  m_jOptions.setLayout(new java.awt.BorderLayout());

  m_jOrderId.setBackground(java.awt.Color.white);
  m_jOrderId.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
  m_jOrderId.setBorder(javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory.createLineBorder(javax.swing.UIManager.getDefaults().getColor("Button.darkShadow")), javax.swing.BorderFactory.createEmptyBorder(1, 4, 1, 4)));
  m_jOrderId.setOpaque(true);
  m_jOrderId.setPreferredSize(new java.awt.Dimension(120, 25));
  m_jOrderId.setRequestFocusEnabled(false);
  m_jButtons.add(m_jOrderId);

  btnCustomer.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/kuser.png"))); // NOI18N
  btnCustomer.setFocusPainted(false);
  btnCustomer.setFocusable(false);
  btnCustomer.setMargin(new java.awt.Insets(8, 14, 8, 14));
  btnCustomer.setMaximumSize(new java.awt.Dimension(35, 36));
  btnCustomer.setMinimumSize(new java.awt.Dimension(35, 22));
  btnCustomer.setPreferredSize(new java.awt.Dimension(35, 25));
  btnCustomer.setRequestFocusEnabled(false);
  btnCustomer.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
          btnCustomerActionPerformed(evt);
      }
  });
  m_jButtons.add(btnCustomer);

  jOrderAttr.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/colorize16.png"))); // NOI18N
  jOrderAttr.setFocusable(false);
  jOrderAttr.setPreferredSize(new java.awt.Dimension(35, 25));
  jOrderAttr.setRequestFocusEnabled(false);
  jOrderAttr.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
          jOrderAttrActionPerformed(evt);
      }
  });
  m_jButtons.add(jOrderAttr);

  jTxtImport.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/fileopen.png"))); // NOI18N
  jTxtImport.setFocusable(false);
  jTxtImport.setMinimumSize(new java.awt.Dimension(35, 22));
  jTxtImport.setPreferredSize(new java.awt.Dimension(35, 25));
  jTxtImport.setRequestFocusEnabled(false);
  jTxtImport.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
          jTxtImportActionPerformed(evt);
      }
  });
  m_jButtons.add(jTxtImport);

  jPanel3.setBorder(javax.swing.BorderFactory.createEtchedBorder());
  jPanel3.setLayout(new javax.swing.BoxLayout(jPanel3, javax.swing.BoxLayout.LINE_AXIS));

  jFirstPage.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/2leftarrow.png"))); // NOI18N
  jFirstPage.setFocusable(false);
  jFirstPage.setPreferredSize(new java.awt.Dimension(35, 25));
  jFirstPage.setRequestFocusEnabled(false);
  jFirstPage.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
          jFirstPageActionPerformed(evt);
      }
  });
  jPanel3.add(jFirstPage);

  jBeforePage.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/1leftarrow.png"))); // NOI18N
  jBeforePage.setFocusable(false);
  jBeforePage.setPreferredSize(new java.awt.Dimension(35, 25));
  jBeforePage.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
          jBeforePageActionPerformed(evt);
      }
  });
  jPanel3.add(jBeforePage);

  jCurrPageIndex.setBackground(new java.awt.Color(255, 255, 255));
  jCurrPageIndex.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
  jCurrPageIndex.setFocusPainted(false);
  jCurrPageIndex.setFocusable(false);
  jCurrPageIndex.setMargin(new java.awt.Insets(0, 0, 0, 0));
  jCurrPageIndex.setMaximumSize(new java.awt.Dimension(50, 25));
  jCurrPageIndex.setMinimumSize(new java.awt.Dimension(50, 25));
  jCurrPageIndex.setPreferredSize(new java.awt.Dimension(40, 25));
  jCurrPageIndex.setRequestFocusEnabled(false);
  jCurrPageIndex.setVerifyInputWhenFocusTarget(false);
  jCurrPageIndex.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
          jCurrPageIndexActionPerformed(evt);
      }
  });
  jPanel3.add(jCurrPageIndex);

  jNextPage.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/1rightarrow.png"))); // NOI18N
  jNextPage.setFocusable(false);
  jNextPage.setPreferredSize(new java.awt.Dimension(35, 25));
  jNextPage.setRequestFocusEnabled(false);
  jNextPage.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
          jNextPageActionPerformed(evt);
      }
  });
  jPanel3.add(jNextPage);

  jLastPage.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/2rightarrow.png"))); // NOI18N
  jLastPage.setFocusable(false);
  jLastPage.setPreferredSize(new java.awt.Dimension(35, 25));
  jLastPage.setRequestFocusEnabled(false);
  jLastPage.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
          jLastPageActionPerformed(evt);
      }
  });
  
  changeLineList = new JToggleButton("L");
  changeLineList.setRequestFocusEnabled(false);
  m_jButtons.add(changeLineList);
  jPanel3.add(jLastPage);

  m_jButtons.add(jPanel3);

  m_jOptions.add(m_jButtons, java.awt.BorderLayout.LINE_START);

  m_jPanelScripts.setLayout(new java.awt.BorderLayout());

  m_jButtonsExt.setLayout(new javax.swing.BoxLayout(m_jButtonsExt, javax.swing.BoxLayout.LINE_AXIS));
  m_jPanelScripts.add(m_jButtonsExt, java.awt.BorderLayout.LINE_END);

  jPrintTempPanel.setLayout(new javax.swing.BoxLayout(jPrintTempPanel, javax.swing.BoxLayout.LINE_AXIS));

  jReportCombo.setFocusable(false);
  jReportCombo.setMaximumSize(new java.awt.Dimension(32767, 25));
  jReportCombo.setMinimumSize(new java.awt.Dimension(70, 25));
  jReportCombo.setPreferredSize(new java.awt.Dimension(120, 25));
  jReportCombo.setRequestFocusEnabled(false);
  jPrintTempPanel.add(jReportCombo);

  jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/fileprint.png"))); // NOI18N
  jButton1.setFocusable(false);
  jButton1.setMaximumSize(new java.awt.Dimension(55, 25));
  jButton1.setMinimumSize(new java.awt.Dimension(35, 25));
  jButton1.setPreferredSize(new java.awt.Dimension(35, 25));
  jButton1.setRequestFocusEnabled(false);
  jButton1.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
          jButton1ActionPerformed(evt);
      }
  });
  jPrintTempPanel.add(jButton1);

  m_jPanelScripts.add(jPrintTempPanel, java.awt.BorderLayout.CENTER);

  m_jOptions.add(m_jPanelScripts, java.awt.BorderLayout.LINE_END);

  m_jPanelBag.setLayout(new java.awt.BorderLayout());
  m_jOptions.add(m_jPanelBag, java.awt.BorderLayout.CENTER);

  m_jPanContainer.add(m_jOptions, java.awt.BorderLayout.NORTH);

  m_jContEntries.setLayout(new java.awt.BorderLayout());

  m_jPanContainer.add(m_jContEntries, java.awt.BorderLayout.LINE_END);

  container.setBorder(javax.swing.BorderFactory.createEmptyBorder(5, 5, 5, 5));
  container.setLayout(new java.awt.BorderLayout());

  jPanel6.setLayout(new java.awt.BorderLayout());

  containerToolbar.setLayout(new java.awt.BorderLayout());
  jPanel6.add(containerToolbar, java.awt.BorderLayout.CENTER);

  jPanel1.setPreferredSize(new java.awt.Dimension(284, 30));

  m_jPrice.setBackground(java.awt.Color.white);
  m_jPrice.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
  m_jPrice.setBorder(javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory.createLineBorder(javax.swing.UIManager.getDefaults().getColor("Button.darkShadow")), javax.swing.BorderFactory.createEmptyBorder(1, 4, 1, 4)));
  m_jPrice.setMaximumSize(new java.awt.Dimension(120, 19));
  m_jPrice.setOpaque(true);
  m_jPrice.setPreferredSize(new java.awt.Dimension(120, 19));
  m_jPrice.setRequestFocusEnabled(false);
  jPanel1.add(m_jPrice);

  m_jTax.setFocusable(false);
  m_jTax.setPreferredSize(new java.awt.Dimension(100, 21));
  m_jTax.setRequestFocusEnabled(false);
  jPanel1.add(m_jTax);

  m_jaddtax.setText("+");
  m_jaddtax.setFocusPainted(false);
  m_jaddtax.setFocusable(false);
  m_jaddtax.setRequestFocusEnabled(false);
  jPanel1.add(m_jaddtax);

  m_jPor.setBackground(java.awt.Color.white);
  m_jPor.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
  m_jPor.setBorder(javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory.createLineBorder(javax.swing.UIManager.getDefaults().getColor("Button.darkShadow")), javax.swing.BorderFactory.createEmptyBorder(1, 4, 1, 4)));
  m_jPor.setMaximumSize(new java.awt.Dimension(1, 0));
  m_jPor.setOpaque(true);
  m_jPor.setPreferredSize(new java.awt.Dimension(1, 0));
  m_jPor.setRequestFocusEnabled(false);
  jPanel1.add(m_jPor);

  jPanel6.add(jPanel1, java.awt.BorderLayout.EAST);
  m_jKeyFactory = new javax.swing.JTextField();
  jPanel1.add(m_jKeyFactory);
  
          m_jKeyFactory.setBackground(javax.swing.UIManager.getDefaults().getColor("Panel.background"));
          m_jKeyFactory.setForeground(javax.swing.UIManager.getDefaults().getColor("Panel.background"));
          m_jKeyFactory.setBorder(null);
          m_jKeyFactory.setCaretColor(javax.swing.UIManager.getDefaults().getColor("Panel.background"));
          m_jKeyFactory.setPreferredSize(new java.awt.Dimension(1, 1));
          m_jKeyFactory.addKeyListener(new java.awt.event.KeyAdapter() {
              public void keyTyped(java.awt.event.KeyEvent evt) {
                  m_jKeyFactoryKeyTyped(evt);
              }
          });

  container.add(jPanel6, java.awt.BorderLayout.PAGE_END);

  m_jPanContainer.add(container, java.awt.BorderLayout.SOUTH);

  add(m_jPanContainer, "order");
  
  splitPane = new JSplitPane();
  splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);
  m_jPanContainer.add(splitPane, BorderLayout.CENTER);
  m_jPanOrder = new javax.swing.JPanel();
  splitPane.setLeftComponent(m_jPanOrder);
  m_jPanelCentral = new javax.swing.JPanel();
  jPanel4 = new javax.swing.JPanel();
  
          m_jPanOrder.setBorder(javax.swing.BorderFactory.createEmptyBorder(5, 5, 5, 5));
          m_jPanOrder.setLayout(new java.awt.BorderLayout());
          
                  m_jPanelCentral.setLayout(new java.awt.BorderLayout());
                  
                          jPanel4.setLayout(new java.awt.BorderLayout());
                          m_jPanelCentral.add(jPanel4, java.awt.BorderLayout.SOUTH);
                          
                                  m_jPanOrder.add(m_jPanelCentral, java.awt.BorderLayout.CENTER);
                                  catcontainer = new javax.swing.JPanel();
                                  splitPane.setRightComponent(catcontainer);
                                  
                                          catcontainer.setLayout(new java.awt.BorderLayout());
                                          splitPane.setDividerLocation(500);
                                                                              
}// </editor-fold>//GEN-END:initComponents

private void m_jKeyFactoryKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_m_jKeyFactoryKeyTyped

  m_jKeyFactory.setText(null);
  stateTransition(evt.getKeyChar());

}//GEN-LAST:event_m_jKeyFactoryKeyTyped




// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnCustomer;
private javax.swing.JPanel catcontainer;
private javax.swing.JPanel container;
private javax.swing.JPanel containerToolbar;
private javax.swing.JButton jBeforePage;
private javax.swing.JButton jButton1;
private javax.swing.JButton jCurrPageIndex;
private javax.swing.JButton jFirstPage;
private javax.swing.JButton jLastPage;
private javax.swing.JButton jNextPage;
private javax.swing.JButton jOrderAttr;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel6;
private javax.swing.JPanel jPrintTempPanel;
private javax.swing.JComboBox jReportCombo;
private javax.swing.JButton jTxtImport;
private javax.swing.JPanel m_jButtons;
private javax.swing.JPanel m_jButtonsExt;
private javax.swing.JPanel m_jContEntries;
private javax.swing.JTextField m_jKeyFactory;
private javax.swing.JPanel m_jOptions;
private javax.swing.JLabel m_jOrderId;
private javax.swing.JPanel m_jPanContainer;
private javax.swing.JPanel m_jPanOrder;
private javax.swing.JPanel m_jPanelBag;
private javax.swing.JPanel m_jPanelCentral;
private javax.swing.JPanel m_jPanelScripts;
private javax.swing.JLabel m_jPor;
private javax.swing.JLabel m_jPrice;
private javax.swing.JComboBox m_jTax;
private javax.swing.JToggleButton m_jaddtax;
private JToggleButton changeLineList;
private JSplitPane splitPane;
// End of variables declaration//GEN-END:variables



class M_inputDeleteAction extends AbstractAction {
  @Override
  public void actionPerformed(ActionEvent e) {
      String sName = m_jPrice.getText();
      if (sName != null && !sName.isEmpty()) {
          sName = (String) sName.subSequence(0, sName.length() - 1);
          m_jPrice.setText(sName);
          if(sName.isEmpty())
          	stateToZero();
      }
  }
}

class M_jInsServingsAction extends AbstractAction {
  @Override
  public void actionPerformed(ActionEvent e) {
      addServings();
  }
}


class M_jDeleteAction extends AbstractAction {

  @Override
  public void actionPerformed(ActionEvent e) {
      if(isEditAble())
        m_jDeleteActionPerformed(e);
  }
}

class M_jDownAction extends AbstractAction {

  @Override
  public void actionPerformed(ActionEvent e) {
      m_jDownActionPerformed(e);
  }
}

class M_jEditLineAction extends AbstractAction {

  @Override
  public void actionPerformed(ActionEvent e) {
      if(isEditAble())
      	if(!changeLineList.isSelected())
              m_jEditLineActionPerformed(e);
      	else
      		m_jMoveLineUpActionPerformed(e);
      		
  }
}

class M_jEditProductAction extends AbstractAction {

  @Override
  public void actionPerformed(ActionEvent e) {
        m_jEditProductActionPerformed(e);
  }
}

class M_jEditLineAttribAction extends AbstractAction {

  @Override
  public void actionPerformed(ActionEvent e) {
      if(isEditAble())
             m_jEditLineAttrib();
  }
}

class M_jFindProdcutAction extends AbstractAction {

  @Override
  public void actionPerformed(ActionEvent e) {
     if(isEditAble())
       m_jListActionPerformed(e);
  }
}


class M_jUpAction extends AbstractAction {

  @Override
  public void actionPerformed(ActionEvent e) {
      m_jUpActionPerformed(e);
  }
}

class M_jEditAttributesAction extends AbstractAction {
  @Override
  public void actionPerformed(ActionEvent e) {
      if(isEditAble())
      	if(!changeLineList.isSelected())
      		jEditAttributesActionPerformed(e);
       	else
       		m_jMoveLineDownActionPerformed(e);
  }
}


class M_jChangeOrderRateAction extends AbstractAction {

  @Override
  public void actionPerformed(ActionEvent e) {
    if(isEditAble())
       changeOrderRate();
  }
}


class M_jQuickSellAction extends AbstractAction {

  @Override
  public void actionPerformed(ActionEvent e) {
      if(isEditAble())
         quickSell();
  }
}

  class M_jChangeOrderTypeAction extends AbstractAction {

  @Override
  public void actionPerformed(ActionEvent e) {
      if(isEditAble())
        changeOrderType();
  }
}

class M_jChangeCoustomerAction extends AbstractAction {

  @Override
  public void actionPerformed(ActionEvent e) {
     if(isEditAble())
       btnCustomerActionPerformed(e);
  }
}

class M_jPrintAction extends AbstractAction {

  @Override
  public void actionPerformed(ActionEvent e) {
    //printReport("Printer.OrderPreview");
   
  }
}

class AddCustomerAction extends AbstractAction {
  @Override
  public void actionPerformed(ActionEvent e) {
     if(isEditAble())
       addNewCustomer();
  }
}

class M_ProductDetailAction extends AbstractAction {
  @Override
  public void actionPerformed(ActionEvent e) {
	  if(!isCustomerView())
	    customerNavigator.setVisible(!customerNavigator.isVisible());
  }
}

class M_SavePageSortAction extends AbstractAction {
  @Override
  public void actionPerformed(ActionEvent e) {
  	if(isEditAble())
  		savePageSort();
  }
}

class M_ProductRefushAction extends AbstractAction {
  @Override
  public void actionPerformed(ActionEvent e) {
  	if(isEditAble())
  		refushOrderLineProduct();
  }
}




//***************************************************************************

private void m_jDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_m_jDeleteActionPerformed

  int i = m_Orderlines.getSelectedIndex();
  if (i < 0) {
      Toolkit.getDefaultToolkit().beep(); // No hay ninguna seleccionada
  } else {
      removeOrderLine(i); // elimino la linea
  }

}//GEN-LAST:event_m_jDeleteActionPerformed

public void savePageSort() {
	orderManager.setOrderLine(m_Orderlines.getOrderLines());
}


public void refushOrderLineProduct() {
	int i = m_Orderlines.getSelectedIndex();
	if(i>=0){
	  OrderLine selected=orderManager.getLine(i);
	  if(selected.getProductID()==null)
		  return;
	  Product oProduct=null;
		try {
			oProduct = dlSales.getProductInfo(selected.getProductID());
			selected.checkProduct(oProduct);
			paintOrderLine(i, selected,false);
		} catch (BasicException e) {
			new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.noproduct")).show(this);
		}
	}
}

public void m_jMoveLineDownActionPerformed(ActionEvent e) {
	int i = m_Orderlines.getSelectedIndex();
	if(i>=0&&i<orderManager.getLinesCount()-1){
	   OrderLine down=orderManager.getLine(i+1);
	   OrderLine selected=orderManager.getLine(i);
	   orderManager.setLine(i, down);
	   orderManager.setLine(i+1, selected);
	   m_Orderlines.setOrderLine(i, down);
	   m_Orderlines.setOrderLine(i+1, selected);
	   m_Orderlines.selectionDown();
	}
}

public void m_jMoveLineUpActionPerformed(ActionEvent e) {
	int i = m_Orderlines.getSelectedIndex();
	if(i>0){
		   OrderLine up=orderManager.getLine(i-1);
		   OrderLine selected=orderManager.getLine(i);
		   orderManager.setLine(i-1, selected);
		   orderManager.setLine(i, up);
		   m_Orderlines.setOrderLine(i-1, selected);
		   m_Orderlines.setOrderLine(i, up);
		   m_Orderlines.selectionUp();
	}
}

public void m_jEditProductActionPerformed(ActionEvent e1) {
	if(isCustomerView())
		return;
	int i = m_Orderlines.getSelectedIndex();
  if (i < 0) {
      Toolkit.getDefaultToolkit().beep(); // no line selected
  } else {
          OrderLine line = orderManager.getLine(i);
          String productId=line.getProductID();
          if(productId!=null&&security.hasPermissionByName(ERPPermission.COMMERCIALOBJECT_Product)){
          try {
				ProductExt product=(ProductExt) dlSales.findByStringId(ProductExt.class, productId);
				if(productCreateDialog==null)
		             productCreateDialog=JEditorWarpDialog.getInstance(this).init(dlSales,new ProductsEditor(dlSales, new DirtyManager()));
		    	 try {
					productCreateDialog.activate();
				} catch (BasicException e) {
					JMessageDialog.showMessage(this, new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.notactive"), e));
		            return;
				} 
		       productCreateDialog.writeValueEdit(product);
          } catch (BasicException e) {
				MessageInf msg = new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.cannotfindcustomer"), e);
	            msg.show(this);
			}
     }
  };
}

private void m_jUpActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_m_jUpActionPerformed

  m_Orderlines.selectionUp();

}//GEN-LAST:event_m_jUpActionPerformed

private void m_jDownActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_m_jDownActionPerformed

  m_Orderlines.selectionDown();

}//GEN-LAST:event_m_jDownActionPerformed

private void btnCustomerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCustomerActionPerformed
  if(isCustomerView())
	  return;
  JCustomerFinder finder = JCustomerFinder.getCustomerFinder(this, dlSales);
  finder.search(m_oOrder.getCustomer());
  finder.setVisible(true);

  try {
      m_oOrder.setCustomer((BusinessPartner) (finder.getSelectedCustomer() == null ? null : dlSales.findByStringId(BusinessPartner.class, finder.getSelectedCustomer().getId())));
  } catch (BasicException e) {
      MessageInf msg = new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.cannotfindcustomer"), e);
      msg.show(this);
  }
  refreshOrder();
}//GEN-LAST:event_btnCustomerActionPerformed


//**888888888888888888888888888888888888888888888888888888888888888

private void quickSell() {
	 if (catalogDialog == null) {
		try {
			catalogDialog = JCatalogKeyBoardDialog.newJDialog(this,
					dlSales, m_jbtnconfig, false);
		} catch (BasicException e) {
			JMessageDialog.showMessage(
					this,
					new MessageInf(MessageInf.SGN_WARNING, AppLocal
							.getIntString("message.notactive"), e));
			catalogDialog = null;
			return;
		}
	} else {
		catalogDialog.reset();
	}
	catalogDialog.setVisible(true);	
	for (Entry<Product,Double> e : catalogDialog.getShoppingCart().getLines().entrySet()) {
			incProduct(e.getValue(),e.getKey());
		}
}

private void changeOrderRate() {
  JChangeRateDialog rantDialog = JChangeRateDialog.getDialog(this, m_oOrder.getM_dPriceRate());
  rantDialog.setVisible(true);
  if (rantDialog.isOk()) {
      Double changedRant = rantDialog.getChangeRate();
      reflushOrder(m_oOrder);
      OrderUtil.changeRate(m_oOrder, changedRant);
  }
  refreshOrder();
}

private void addNewCustomer() {
	if(isCustomerView())
		return;
	 if(customerCreateDialog==null)
		 customerCreateDialog=JEditorWarpDialog.getInstance(this).init(dlSales,new CustomersEditor(dlSales, new DirtyManager()));
	 try {
		customerCreateDialog.activate();
	} catch (BasicException e) {
		JMessageDialog.showMessage(this, new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.notactive"), e));
      return;
	}
	 customerCreateDialog.writeValueInsert(null);
	 if(customerCreateDialog.getRetObj()!=null){
       m_oOrder.setCustomer((BusinessPartner) customerCreateDialog.getRetObj());
       refreshOrder();
   }
}

private void addNewProduct(String code){
	if(isCustomerView())
		return;
	 if(productCreateDialog==null)
       productCreateDialog=JEditorWarpDialog.getInstance(this).init(dlSales,new ProductsEditor(dlSales, new DirtyManager()));
	 try {
		productCreateDialog.activate();
	} catch (BasicException e) {
		JMessageDialog.showMessage(this, new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.notactive"), e));
      return;
	} 
	 Properties prop=new Properties();
	 prop.put(I_Product.REFERENCE, code);
	 productCreateDialog.writeValueInsert(prop);
   if(productCreateDialog.getRetObj()!=null){
       Product product=(Product) productCreateDialog.getRetObj();
       this.incProduct(product);
   }
}


private void jEditAttributesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jEditAttributesActionPerformed

  int i = m_Orderlines.getSelectedIndex();
  if (i < 0) {
      Toolkit.getDefaultToolkit().beep(); // no line selected
  } else {
      try {
          OrderLine line = orderManager.getLine(i);
          JProductAttEdit attedit = JProductAttEdit.getAttributesEditor(this, dlSales);
          attedit.editAttributes(line.getProductAttSetId(), line.getProductAttSetInstId(),line.getProductID());
          attedit.setVisible(true);
          if (attedit.isOK()) {
              // The user pressed OK
              String beforeAttrsetinst=line.getProductAttSetInstId();
              String endAttrsetinst=attedit.getAttributeSetInstance().getId();
              if((beforeAttrsetinst==null&&endAttrsetinst==null)||beforeAttrsetinst!=null&&beforeAttrsetinst.equals(endAttrsetinst))
                  return;
              line.setProductAttSetInstId(endAttrsetinst);
              line.setProductAttSetInstDesc(attedit.getAttributeSetInstance().getDescription());
              OrderUtil.choiceProductAttibuteValuePrice(m_oOrder,line,attedit.getAttributeSetInstance());
              if(orderLineExistCheck(line, true)){
                 removeOrderLine(i); // elimino la linea
              }else{
                  paintOrderLine(i, line,true);
              }
          }
      } catch (BasicException ex) {
          MessageInf msg = new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.cannotfindattributes"), ex);
          msg.show(this);
      }
  }

}//GEN-LAST:event_jEditAttributesActionPerformed

private void jFirstPageActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jFirstPageActionPerformed
  orderManager.pageFirst();
}//GEN-LAST:event_jFirstPageActionPerformed

private void jBeforePageActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBeforePageActionPerformed
   orderManager.pageUp();
}//GEN-LAST:event_jBeforePageActionPerformed

private void jNextPageActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jNextPageActionPerformed
  orderManager.pageDown();
}//GEN-LAST:event_jNextPageActionPerformed

private void jLastPageActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jLastPageActionPerformed
   orderManager.pageEnd();
}//GEN-LAST:event_jLastPageActionPerformed

private void jCurrPageIndexActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCurrPageIndexActionPerformed
       Double advCode = JNumberDialog .showEditNumber(this,
          AppLocal.getIntString("Label.inputPageNumber"),
          AppLocal.getIntString("Label.inputPageNumber"));
      if(advCode!=null){
           int pageIndex=advCode.intValue();
           orderManager.selectPage(pageIndex);
      }
}//GEN-LAST:event_jCurrPageIndexActionPerformed

private void jTxtImportActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTxtImportActionPerformed
  JTxtImportDialog.showDialog(this);
}//GEN-LAST:event_jTxtImportActionPerformed

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
Object object=jReportCombo.getSelectedItem();
if(object!=null){
    String report=(String) ((ComboBoxValEntry)object).getKey();
   printReport(report,getActiveOrder(),null);
}
}//GEN-LAST:event_jButton1ActionPerformed


private void changeOrderType() {
	if(isCustomerView())
		return;
   reflushOrder(m_oOrder); 
  if (m_oOrder.getLinesCount() > 0) {
      MessageInf msg = new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.theTickeMustEmpty"));
      msg.show(this);
      return;
  }
  if (Order.ORDERBEARING_NORMAL == m_oOrder.getOrderType()) {
      m_oOrder.setOrderType(Order.ORDERBEARING_REVERSE);
  } else if (Order.ORDERBEARING_REVERSE == m_oOrder.getOrderType()) {
      m_oOrder.setOrderType(Order.ORDERBEARING_NORMAL);
  }
  printPartialTotals();
}


private void m_jListActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_m_jListActionPerformed
  Product prod = JProductFinder.showMessage(JPanelOrder.this, dlSales);
  if(prod!=null)
    buttonTransition(prod);
}//GEN-LAST:event_m_jListActionPerformed


private void refreshOrderLineSelectedState(){
  int i = m_Orderlines.getSelectedIndex();
  if (i >= 0) {
     OrderLine selectedline = orderManager.getLine(i);
      if (selectedline != null ) {
          orderLineSelectedChanged(selectedline);
          //productDetail.baseBeanChanged(KeyBuilder.getKey(selectedline.getProductID()), null);
      }
  }
}

private void m_jEditLineAttrib() { 
  int i = m_Orderlines.getSelectedIndex();
  if (i < 0) {
      Toolkit.getDefaultToolkit().beep(); // no line selected
  } else {
      try {
          OrderLine line = orderManager.getLine(i);
          JTicketLinePropEdit propEdit = JTicketLinePropEdit.getPropEdit(this, line.getProperty(OrderLine.OrderlINE_EXTPROP, ""));
          propEdit.setVisible(true);
          if (propEdit.isOK()) {
              line.setProperty(OrderLine.OrderlINE_EXTPROP, propEdit.getRetProps());
              paintOrderLine(i, line,false);
          }
      } catch (BasicException ex) {
          MessageInf msg = new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.cannotfindattributes"), ex);
          msg.show(this);
      }
  }
}

private void m_jEditLineActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_m_jEditLineActionPerformed
  int i = m_Orderlines.getSelectedIndex();
  if (i < 0) {
      Toolkit.getDefaultToolkit().beep(); // no line selected
  } else {
      try {
          OrderLine selectedline = orderManager.getLine(i);
              OrderLine newline = JOrderLineEditDialog.showMessage(this, m_App, selectedline,m_oOrder.getDefineType(), dlSales);
              if (newline != null) {
                  // line has been modified
                  paintOrderLine(i, newline,false);
              }
          //}
      } catch (BasicException e) {
          new MessageInf(e).show(this);
      }
  }

}//GEN-LAST:event_m_jEditLineActionPerformed

private void jOrderAttrActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jOrderAttrActionPerformed
   try {
          JProductAttEdit attedit = JProductAttEdit.getAttributesEditor(this,dlSales);
          attedit.editAttributes(m_oOrder.getDefineType().getAttributesetid(), m_oOrder.getAttsetinstid(),isEditAble());
          attedit.setVisible(true);
          if (attedit.isOK()) {
              // The user pressed OK
              m_oOrder.setAttsetinstid(attedit.getAttributeSetInstance().getId());
              m_oOrder.setProperty(Order.ATTRIBUTESET_InstDescription, attedit.getAttributeSetInstance().getDescription());
          }
      } catch (BasicException ex) {
          MessageInf msg = new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.cannotfindattributes"), ex);
          msg.show(this);
      }
}//GEN-LAST:event_jOrderAttrActionPerformed

public abstract void orderLineSelectedChanged(OrderLine line);

public void addListSelectionListener(ListSelectionListener l) {
  m_Orderlines.addListSelectionListener(l);
}

public void removeListSelectionListener(ListSelectionListener l) {
  m_Orderlines.removeListSelectionListener(l);
}

@Override
public boolean isEditAble() {
 if(!orderManager.isEditAble())
     return false;
 boolean isStartState=AppLocal.getIntString(OrderState.ORDERSTATE_Start).equalsIgnoreCase(m_oOrder.getCurrentState());
 if(!isStartState)
     return false;
 boolean userEditAble=RoleUtil.hasOrderTypePermission((AppUser) m_App.getAppUserView().getUser(),m_oOrder.getDefineType().getId(), RoleUtil.getLocalePermissionName(UserOrderTypePermission.ORDERTYPEEVENT_Edit));
  if(!userEditAble)
      return false;
 return true;
}

@Override
public void addOrderLines(java.util.List<OrderLine> lines) {
     java.util.List<OrderLine> mustInsertList=new ArrayList();
     for(OrderLine oLine:lines){
      if (!orderLineExistCheck(oLine, false))
          mustInsertList.add(oLine);
    }
  orderManager.addLines(mustInsertList);
}

public I_DataLogicSystem getDlSystem() {
  return dlSystem;
}

public JProductFinder getProductFinder() {
  if(productFinder==null)
      productFinder=JProductFinder.getInstance(JPanelOrder.this, dlSales,JProductFinder.PRODUCT_ALL);
  return productFinder;
}

private void addServings() {
  try {
      JServingsEditorDialog servingsEditorDialog = JServingsEditorDialog.getDialog(this);
      servingsEditorDialog.init(dlSales, null,m_oOrder.getDefineType().isServiceCheck());
      servingsEditorDialog.setVisible(true);
      if (servingsEditorDialog.isOK()) {
          Serving retServings = servingsEditorDialog.getServings();
          if (retServings != null) {
              String tcid = ((TaxCategory) taxcategoriesmodel.getSelectedItem()).getID();
              Tax tax = taxeslogic.getTaxInfo(tcid, m_oOrder.getCustomer());
              addOrderLine(new OrderLine(retServings, tax, m_oOrder.getM_dPriceRate()));
          }
      }
  } catch (BasicException ex) {
      JMessageDialog.showMessage(this, new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.notactive"), ex));
      return;
  }
}

public JOrdersBag getM_Ordersbag() {
	return m_Ordersbag;
}

@Override
public void baseBeanChanged(IKeyed<String> productID, Product o) {
	if(!isEditAble())
      return;
	try {
		incProduct(dlSales.getProductInfo(productID.getKey()));
	} catch (BasicException e) {
		JMessageDialog.showMessage(this, new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.notactive"), e));
		e.printStackTrace();
	}
	
}

@Override
public void print(String sresourcename) {
	
}


public boolean isCustomerView(){
	return m_App.isCustomerView();
}

@Override
public String getModelName() {
	
	return ERP_UI_Swing_Model.MODEL_NAME;
}

protected ERP_UI_Swing_Model mode;
protected I_SecurityManager security;
protected int extPermission;

@Override
public void setModel(ERP_UI_Swing_Model mode) {
	this.mode=mode;
	security=mode.getModelSecurityManager();
	
}

protected ERP_UI_Swing_Model getModel(){
	return mode;
}

public I_DataLogicReceipts getDlReceipts() {
	return dlReceipts;
}

@Override
public I_SecurityManager getSecurityManager() {
	return security;
}


@Override
public void setExtPermission(int permission) {
	this.extPermission=permission;
}

@Override
public boolean hasExtPermission(int srcType) {
	return (extPermission^srcType)==srcType;
}

@Override
public String getBaseSecurityName() {
	return this.getClass().getName();
}

/**
 * 以下权限进定
 */



}
